﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using System.Diagnostics;
using DoubleH.Utility;
using System.Collections.ObjectModel;
using System.Data;
using DoubleH.Utility.Configuration;

namespace SalesOrderS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        Table.SalesOrderS order = null;
        DataTableText tableText = DataTableText.销售单据商品编辑;
        //Table.CorS vipCorS = null;

        public void Init(Table.SalesOrderS.EnumFlag flag, Table.SalesOrderS obj)
        {
            order = obj ?? new Table.SalesOrderS(flag);
            InitVar();

            productSListInfoObject.Init(DoubleHConfig.UserConfig.GetUserUIparams(tableText));
            productSListInfoObject.ShowAverage = false;
            productSListInfoObject.MustHasStoreS = false;
            corSelect1.Init(true);
            userSelect1.Init(Table.UserS.EnumFlag.经办人);
            uCUniqueSInvoice.Init(Table.UniqueS.EnumFlag.发票定义);

            InitMenu();
            InitEvent();
            InitOrder();
        }

        private void InitMenu()
        {
            MenuItem mi1 = new MenuItem();
            mi1.Header = "选择价格";
            mi1.Click += (ss, ee) =>
            {
                Table.ProductS ps = productSListInfoObject.GetSelectedObject();
                if (ps == null)
                {
                    MessageWindow.Show("请选择商品");
                    return;
                }

                ProductS.GetWholesalePrice gwp = new ProductS.GetWholesalePrice(ps);
                gwp.ShowDialog();
            };

            MenuItem mi2 = new MenuItem();
            mi2.Header = "选择会员";
            mi2.Click += (ss, ee) =>
            {
                //if (!IsSelectedProduct())
                //    return;

                CorS.GetVip vip = new CorS.GetVip();
                vip.Init();
                vip.ShowDialog();
                if (vip.SelectedObject == null)
                {
                    order.VipId = -1;
                    labelVip.Content = string.Empty;
                }
                else
                {
                    order.VipId = vip.SelectedObjectId;
                    labelVip.Content = vip.SelectedObject._VipUniqueSName + "(" + vip.SelectedObject.VipNO + ")";
                }
            };
            productSListInfoObject.BodyMenu.Items.Insert(0, mi1);
            productSListInfoObject.BodyMenu.Items.Insert(1, mi2);

            productSListInfoObject.BodyMenu.Items.Insert(2, new Separator());
        }

        private void InitOrder()
        {
            Debug.Assert(order != null);

            bool b = (order.Enable > Table.SalesOrderS.EnumEnable.下单);
            dateTimeUpDownKaiDan.IsReadOnly = b;
            dateTimeUpDownDaoHuo.IsReadOnly = b;
            corSelect1.IsEnabled = !b;
            userSelect1.IsReadOnly = b;
            textBoxNote.IsReadOnly = b;

            checkBoxDefault.IsEnabled = !b;
            buttonZuoFei.IsEnabled = !b;
            buttonSave.IsEnabled = !b;
            uCUniqueSInvoice.IsEnabled = !b;
            buttonShenHe.IsEnabled = !b;
            if (order.Flag == Table.SalesOrderS.EnumFlag.销售订单)
                doubleUpDownAdvance.IsEnabled = !b;
            else
                doubleUpDownAdvance.IsEnabled = false;

            BaoXiu.IsEnabled = (order.Flag != Table.SalesOrderS.EnumFlag.销售退货单);
            dateTimeUpDownKaiDan.Value = order.OrderDateTime;
            dateTimeUpDownDaoHuo.Value = order.ArrivalDateTime;
            label1OrderNo.Content = order.OrderNO;
            corSelect1.SelectedObjectId = order.CorSId;
            uCUserSelectForCorS.Init(true, order.CorSId);
            uCUserSelectForCorS.SelectedObjectId = order.UserSIdForCorS;
            userSelect1.SelectedValue = order.OperatorerSId;
            textBoxNote.Text = order.Note;
            textBoxAddress.Text = order.Address;
            BaoXiu.Value = (int)order.BaoXiu;
            uCUniqueSInvoice.SelectedObjectId = order.InvoiceType;
            doubleUpDownAdvance.Value = order.Advance;

            productSListInfoObject.ItemsSource = order.ProductSList;
            productSListInfoObject.IsReadOnly = false;
            switch (order.Flag)
            {
                case Table.SalesOrderS.EnumFlag.销售询价单:
                    productSListInfoObject.SetProductSType = ProductS.GetProductS.EnumProductS.询价单商品;
                    buttonShenHe.IsEnabled = false;
                    break;

                default:
                    productSListInfoObject.SetProductSType = ProductS.GetProductS.EnumProductS.可销售商品;
                    break;
            }

            if (order.Id == -1)
                productSListInfoObject.EnableText = string.Empty;
            else
            {
                switch (order.Enable)
                {
                    case Table.SalesOrderS.EnumEnable.审核:
                    case Table.SalesOrderS.EnumEnable.入账:
                    case Table.SalesOrderS.EnumEnable.作废:
                    case Table.SalesOrderS.EnumEnable.预付款:
                        productSListInfoObject.EnableText = order.Enable.ToString();
                        productSListInfoObject.IsReadOnly = true;
                        break;
                    default:
                        productSListInfoObject.EnableText = order.Id == -1 ? string.Empty : order.Enable.ToString();
                        break;
                }
            }
        }

        private void InitVar()
        {
            switch (order.Flag)
            {
                case Table.SalesOrderS.EnumFlag.销售询价单:
                    tableText = DataTableText.销售询价单商品编辑;
                    productSListInfoObject.ShowAverage = true;
                    productSListInfoObject.CanNegativeSales = true;
                    buttonNew.Content = "询价单（新）";
                    break;
                case Table.SalesOrderS.EnumFlag.销售退货单:
                    labelDate.Content = "退货日期";
                    productSListInfoObject.Foreground = Brushes.Red;
                    buttonNew.Content = "退货单（新）";
                    break;
                case Table.SalesOrderS.EnumFlag.赠品出库单:
                    tableText = DataTableText.赠品商品编辑;
                    expanderNew.IsEnabled = false;
                    break;
                case Table.SalesOrderS.EnumFlag.销售订单:
                    buttonNew.Content = "销售单（新）";
                    break;
            }

            string name = order.Flag.ToString();
            this.Title = name;
            labelTitle.Content = name;
        }

        private void InitEvent()
        {
            this.Closing += (ss, ee) => ee.Cancel = !DataSaveOrCancel();
            corSelect1.CorSChanged += (ee) => ChangedCorS();
            buttonPre.Click += (ss, ee) => OrderPre();
            buttonNext.Click += (ss, ee) => OrderNext();
            doubleUpDownDefault.ValueChanged += (ss, ee) => ChangeQuantity();
            checkBoxDefault.Checked += (ss, ee) => ChangeQuantity();
            buttonZuoFei.Click += (ss, ee) => OrderZuoFei();
            buttonSave.Click += (ss, ee) => OrderSave();
            buttonShenHe.Click += (ss, ee) => OrderShenHe();
            buttonPrint.Click += (ss, ee) => PrintOrder();

            buttonNew.Click += (ss, ee) =>
            {
                OrderNew();
                expanderNew.IsExpanded = false;
            };
            buttonCopyXJ.Click += (ss, ee) =>
                {
                    if (order.Id == -1)
                        return;

                    order = (Table.SalesOrderS)order.CloneObject(new object[] { Table.SalesOrderS.EnumFlag.销售询价单 });
                    OrderCopy();
                };
            buttonCopyPF.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.SalesOrderS)order.CloneObject(new object[] { Table.SalesOrderS.EnumFlag.销售订单 });
                //order.Flag = Table.SalesOrderS.EnumFlag.销售订单;
                OrderCopy();
            };
            buttonCopyTH.Click += (ss, ee) =>
            {
                if (order.Id == -1)
                    return;

                order = (Table.SalesOrderS)order.CloneObject(new object[] { Table.SalesOrderS.EnumFlag.销售退货单 });
                //order.Flag = Table.SalesOrderS.EnumFlag.销售退货单;
                OrderCopy();
            };
            expanderNew.MouseLeave += (ss, ee) => { expanderNew.IsExpanded = false; };
        }

        private void ChangedCorS()
        {
            order.CorSId = corSelect1.SelectedObjectId;
            uCUserSelectForCorS.Init(true, order.CorSId);
            textBoxAddress.Text = corSelect1.SelectedObject.Address;
        }

        private void ChangeQuantity()
        {
            if (checkBoxDefault.IsChecked == true)
                productSListInfoObject.ResetAllProductQuantity((double)doubleUpDownDefault.Value);
        }

        private void OrderPre()
        {
            Table.SalesOrderS p = Table.SalesOrderS.GetPreObject(order.Id, order.Flag);
            if (p == null)
                MessageWindow.Show("没有上一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNext()
        {
            FCNS.Data.Table.SalesOrderS p = Table.SalesOrderS.GetNextObject(order.Id, order.Flag);

            if (p == null)
                MessageWindow.Show("没有下一条记录了");
            else
            {
                order = p;
                InitOrder();
            }
        }

        private void OrderNew()
        {
            if (DataSaveOrCancel())
            {
                order = new FCNS.Data.Table.SalesOrderS(order.Flag);
                InitOrder();
            }
        }

        private void OrderZuoFei()
        {
            //如果订单还没有保存到数据库就没必要删除了,免去控件的刷新
            if (order.Id == -1)
                return;

            if (MessageWindow.Show("", "确定要作废此单据吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Table.DataTableS.EnumDatabaseStatus result = order.ZuoFei();
                MessageWindow.Show(result.ToString());
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    OrderNew();
            }
        }

        private void OrderSave()
        {
            order.OrderDateTime = dateTimeUpDownKaiDan.Value.Value;
            order.ArrivalDateTime = dateTimeUpDownDaoHuo.Value.Value;
                order.OperatorerSId = userSelect1.SelectedObjectId;
            order.Note = textBoxNote.Text;
            order.Address = textBoxAddress.Text;
            order.BaoXiu = BaoXiu.Value.Value;
            order.Advance = doubleUpDownAdvance.Value.Value;
            order.InvoiceType = uCUniqueSInvoice.SelectedObjectId;
                order.UserSIdForCorS = uCUserSelectForCorS.SelectedObjectId;

            //验证库存和最高、最低销售价
            if (order.Flag == Table.SalesOrderS.EnumFlag.销售订单)
            {
                List<Table.ProductS> thePrice = new List<Table.ProductS>();
                //List<Table.ProductS> theQuantity = new List<Table.ProductS>();
                foreach (Table.ProductS ps in productSListInfoObject.ItemsSource)
                {
                    if (ps.WholesalePriceMaximum != 0 && ps._TempPrice > ps.WholesalePriceMaximum)
                        thePrice.Add(ps);
                    else if (ps.WholesalePriceMinimum != 0 && ps._TempPrice < ps.WholesalePriceMinimum)
                        thePrice.Add(ps);
                    //else if (!Table.SysConfig.SysConfigParams.NegativeSales && ps.Flag != Table.ProductS.EnumFlag.免库存 && ps._TempQuantity > ps._Quantity)
                    //    theQuantity.Add(ps);//记得‘免库存’商品不要验证库存数量了
                }
                for (int i = 0; i < productSListInfoObject.ItemsSource.Count; i++)
                {
                    if (thePrice.Contains(productSListInfoObject.ItemsSource[i]))
                    {
                        DataGridRow row = (DataGridRow)productSListInfoObject.DataGrid.ItemContainerGenerator.ContainerFromIndex(i);
                        row.Foreground = Brushes.Red;
                    }
                    //else if (theQuantity.Contains(productSListInfoObject.ItemsSource[i]))
                    //{
                    //    DataGridRow row = (DataGridRow)productSListInfoObject.DataGrid.ItemContainerGenerator.ContainerFromIndex(i);
                    //    row.Foreground = Brushes.Red;
                    //}
                }
                if (thePrice.Count > 0 )
                {
                    if (MessageWindow.Show("", "商品销售价验证不通过,是否继续?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        return;
                }
            }
            Table.DataTableS.EnumDatabaseStatus result;
            if (order.Id == -1)
                result = order.Insert();
            else
                result = order.Update();

            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());

            productSListInfoObject.CalcQuantityAndMoneyOnBottom();
        }

        private void OrderShenHe()
        {
            if (order.Id == -1)
            {
                MessageWindow.Show("请先保存单据");
                return;
            }

            order.AuditorUserSId = Table.UserS.LoginUser.Id;
            Table.DataTableS.EnumDatabaseStatus result = order.UpdateTo(Table.SalesOrderS.EnumEnable.审核);
            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                InitOrder();
            else
                MessageWindow.Show(result.ToString());
        }

        private bool DataSaveOrCancel()
        {
            if (string.IsNullOrEmpty(label1OrderNo.Content.ToString()) && productSListInfoObject.HasItems)
            {
                switch (MessageBox.Show("是否保存单据?", "", MessageBoxButton.YesNoCancel))
                {
                    case MessageBoxResult.Yes:
                        OrderSave();
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
        }

        private void OrderCopy()
        {
            InitVar();
            order.Enable = Table.SalesOrderS.EnumEnable.下单;
            order.Id = -1;
            InitOrder();
            label1OrderNo.Content = "";
            dateTimeUpDownKaiDan.Value = DateTime.Now;
            dateTimeUpDownDaoHuo.Value = DateTime.Now;
            expanderNew.IsExpanded = false;
        }

        private void PrintOrder()
        {
            DoubleH.Utility.Print.PrintForm.ShowPrint(order, (DataTableText)Enum.Parse(typeof(DataTableText), order.Flag.ToString()), "销售\\" + order.Flag.ToString() + ".frx");
        }
    }
}